package Algorithm.Dp.leetcode42;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Deque;

//https://leetcode-cn.com/problems/trapping-rain-water/

class Solution {
    public int trap(int[] height) {

        int[] maxLeft = new int[height.length];
        int[] maxRight = new int[height.length];

        for(int i=0;i<height.length;i++){
            maxLeft[i] = (i==0?height[i]:Math.max(maxLeft[i-1],height[i]));
        }

        for(int i=height.length-1;i>-1;i--){
            maxRight[i] = i==height.length-1?height[i]:Math.max(maxRight[i+1],height[i]);
        }

        int sum = 0;
        for(int i=0;i<height.length;i++){
            sum = sum + Math.min(maxLeft[i],maxRight[i]) - height[i];
        }

        return sum;
    }
}

public class MainClass {
    public static int[] stringToIntegerArray(String input) {
        input = input.trim();
        input = input.substring(1, input.length() - 1);
        if (input.length() == 0) {
            return new int[0];
        }

        String[] parts = input.split(",");
        int[] output = new int[parts.length];
        for(int index = 0; index < parts.length; index++) {
            String part = parts[index].trim();
            output[index] = Integer.parseInt(part);
        }
        return output;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = in.readLine()) != null) {
            int[] height = stringToIntegerArray(line);

            int ret = new Solution().trap(height);

            String out = String.valueOf(ret);

            System.out.print(out);
        }
    }
}
